export const debounce = function(fn, delay, now) {
  var t = null,
    res = null;

  var debounced = function () {
    var _self = this,
      args = arguments;

    if (t) {
      clearTimeout(t);
    }
    // 是否立即执行一次响应
    if (now) {
      // 记录下是否是第一次进入防抖
      var exec = !t;
      // 生成一个计时器用于判断是否第一次进入防抖
      t = setTimeout(function() {
        // 当时间超过延迟时清除定时器以下次进入时再次立即执行
        clearTimeout(t);
        t = null;
      }, delay);
      
      if (exec) {
        res = fn.apply(_self, args);
      } else {
        t = setTimeout(function(){
          fn.apply(_self, args);
        }, delay);
      }
    } else {
      t = setTimeout(function(){
        res = fn.apply(_self, args);
      }, delay);
    }

    return res;
  }

  debounced.remove = function() {
    clearTimeout(t);
    t = null;
  }

  return debounced;
}

export const throttle = function(fn, delay) {

  var t = null,
    // 获取到节流函数绑定时的时间戳
    begin = new Date().getTime(),
    res;

  var throttled = function() {
    var _self = this,
      args = arguments,
      now = new Date().getTime();

    // 清除上一次绑定的延迟事件
    // 本次触发会再次绑定
    clearTimeout(t);

    if (now - begin > delay) {
      // 当前触发时间与上次触发时间之差大于延迟时间
      // 直接响应事件
      res = fn.apply(_self, args);
      begin = now;
    } else {
      t = setTimeout(function() {
        res = fn.apply(_self, args);
      }, delay)
    }
    return res;
  }

  throttled.remove = function () {
    clearTimeout(t);
    t = null;
  }
  return throttled;
}